#include "netset.h"
#include <QDebug>
NetSet::NetSet(QString ipcon)
{
    ser_sock = new QTcpServer(this);
    cli_sock = new QTcpSocket(this);

    QStringList sl = ipcon.split(':');
    ip = sl[0];
    port = sl[1].toShort();

    qDebug() << ip << "," << port;

    //连接监听失败的错误信号到槽函数
    //connect(ser_sock, &QTcpServer::acceptError, this, &NetSet::netSetSendListenErrorMain);
}

NetSet::~NetSet()
{
    if(ser_sock != nullptr)
        ser_sock->deleteLater();

    if(cli_sock != nullptr)
        cli_sock->deleteLater();
}

void NetSet::mainWindowListenCon()
{
    //TCP服务器
    bool isListen = ser_sock->listen(QHostAddress(ip), port);
    //qDebug() << "start";
    if(isListen){
        connect(ser_sock,&QTcpServer::newConnection,[=](){
            //获取通信套接字
            cli_sock = ser_sock->nextPendingConnection();
            qDebug() << "连接";
            emit netConnect();

            //接收区有信息，则发送信号到mianwindow
            connect(cli_sock,&QTcpSocket::readyRead,[=](){
                QString buf = cli_sock->readAll();
                //qDebug() << buf;
                emit netSetSendDataToMainWindow(buf);
            });

            //断开连接触发disconnected信号，断开连接在cli_sock的信号并赋空指针，向mainwindow发送断开连接信号
            connect(cli_sock,&QTcpSocket::disconnected,[=](){
                disconnect(cli_sock,&QTcpSocket::readyRead,0,0);

                emit netDisconnect();
            });
        });
    }
}

void NetSet::netSetRecvMainWindow(QString info)
{
    if(cli_sock->isOpen()){
        //如果cli_sock连接，则发送指令
        cli_sock->write(info.toUtf8());
    }
}

void NetSet::netSetSendListenErrorMain(QAbstractSocket::SocketError socketError)
{
    //发送错误信号到主界面
    emit netListenDefeat(socketError);
}
